/**
* 函数节流
* @param {function} fn 函数
* @param {number} t 间隔时间（毫秒）
* @return {function}
*/
export const throttle = (fn: { apply: (arg0: any, arg1: any[]) => void }, t: number) => {
    let flag = true
    const interval = t || 500
    return function (this: any, ...args: any) {
        if (flag) {
            fn.apply(this, args)
            flag = false
            setTimeout(() => {
                flag = true
            }, interval)
        }
    }
}

/*函数防抖*/
export const debounce = (fn: { apply: (arg0: any, arg1: any) => void }, t: number) => {
    let timeId: any = null
    const delay = t || 500
    return function (this: any, ...args: any) {
        if (timeId) {
            clearTimeout(timeId)
        }
        timeId = setTimeout(() => {
            timeId = null
            fn.apply(this, args)
        }, delay)
    }
}

export const formatTime = (date: Date) => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return (
        [year, month, day].map(formatNumber).join('/') +
        ' ' +
        [hour, minute, second].map(formatNumber).join(':')
    )
}

const formatNumber = (n: number) => {
    const s = n.toString()
    return s[1] ? s : '0' + s
}


// 时间戳转换成时间格式
export enum FormatsEnums {
    YMD = 'Y-m-d',
    YMDHIS = 'Y-m-d H:i:s',
    _YMD = 'Y年m月d日',
    _YMDHIS = 'Y年m月d日 H时i分'
}

export const dateFormat = function (timestamp: number, formats: FormatsEnums): string {
    // formats格式包括
    // 1. Y-m-d
    // 2. Y-m-d H:i:s
    // 3. Y年m月d日
    // 4. Y年m月d日 H时i分
    formats = formats || 'Y-m-d';

    const zero = function (value: number): string | number {
        if (value < 10) {
            return '0' + value;
        }
        return value;
    };

    const myDate = timestamp ? new Date(timestamp) : new Date();

    const year = myDate.getFullYear();
    const month = zero(myDate.getMonth() + 1);
    const day = zero(myDate.getDate());

    const hour = zero(myDate.getHours());
    const minite = zero(myDate.getMinutes());
    const second = zero(myDate.getSeconds());

    return formats.replace(/Y|m|d|H|i|s/ig, function (matches: string): any {
        // console.log(matches)
        let i: any = {
            Y: year,
            m: month,
            d: day,
            H: hour,
            i: minite,
            s: second
        }
        let flag = i[matches]
        return flag;
    });
};
